package com._4pd.demo.formal.watcher;

import com._4pd.demo.formal.crd.AiOperator;
import com._4pd.demo.formal.crd.AiOperatorStatus;
import com._4pd.demo.formal.K8sClient;
import com._4pd.demo.formal.entity.K8sCommonResource;
import com._4pd.demo.formal.template.AiTemplateRender;
import com._4pd.demo.formal.template.JinJaRender;
import io.fabric8.kubernetes.api.model.Event;
import io.fabric8.kubernetes.api.model.GenericKubernetesResource;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientException;
import io.fabric8.kubernetes.client.WatcherException;
import io.fabric8.kubernetes.client.dsl.NamespaceableResource;
import io.fabric8.kubernetes.client.dsl.Resource;
import io.fabric8.kubernetes.client.dsl.base.ResourceDefinitionContext;
import org.yaml.snakeyaml.Yaml;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.function.UnaryOperator;

public class AiOperatorWatcher2 extends StatusWatcher<AiOperator> {
    private AiTemplateRender aiTemplateRender = new JinJaRender();

    public AiOperatorWatcher2(K8sClient client) throws IOException {
        super(client);
    }

    @Override
    void AddedAction(AiOperator resource) {
        KubernetesClient client = this.client.getClient();
        try {
            String resourceName = resource.getMetadata().getName();
            String resourceYaml = aiTemplateRender.render(resource);

            ResourceDefinitionContext rdc = new Yaml().loadAs(resourceYaml, K8sCommonResource.class).buildResourceDefinitionContext();
            // 创建template，标记 crd name
            Resource<GenericKubernetesResource> resourceResource = client.genericKubernetesResources(rdc)
                    .inNamespace("airflow").load(new ByteArrayInputStream(resourceYaml.getBytes()));

            if (client.genericKubernetesResources(rdc).inNamespace("airflow").withName(resourceName).isReady()) {
                System.out.println("resource: " + " [" + resourceName + "] " + " already exist");
                return;
            }
            //标记 crd 信息
            NamespaceableResource<AiOperator> aiOperatorResource = client.resource(resource);
            AiOperator aiOperator = aiOperatorResource.patchStatus();
            Map<String, String> labels = aiOperator.getMetadata().getLabels();
            aiOperator.getStatus().setAreWeGood(true);
            labels.put("task", String.valueOf(resourceName));
            labels.put("sub_task_type", rdc.getKind() + "_" + rdc.getGroup() + "_" + rdc.getVersion());
            aiOperatorResource.patch(aiOperator);




            System.out.println(resourceYaml);
            GenericKubernetesResource genericKubernetesResource = resourceResource.get();
            genericKubernetesResource.getMetadata().getLabels().put("task", String.valueOf(resourceName));
            genericKubernetesResource.getAdditionalProperties().put("status",new HashMap<>());
            resourceResource.create();


//           注册一个子资源状态的监听
            this.client.registerResourceWatcher(rdc.getVersion(),rdc.getKind());

        } catch (KubernetesClientException e) {
            e.printStackTrace();
            client.resources(AiOperator.class).inNamespace("airflow").withName(resource.getMetadata().getName()).editStatus(aiOperator -> {
                aiOperator.getStatus().setAreWeGood(true);
                aiOperator.getStatus().setHtmlConfigMap("aiOperator.getStatus().setHtmlConfigMap111");
                aiOperator.getStatus().setErrorMessage(e.getMessage());
                return aiOperator;
            });
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    void ModifiedAction(AiOperator resource) {
        System.out.println(resource);
        System.out.println("ModifiedAction");
    }

    @Override
    void DeletedAction(AiOperator resource) {
        String[] split = resource.getMetadata().getLabels().get("sub_task_type").split("_");
        Resource<GenericKubernetesResource> resourceResource = client.getClient().genericKubernetesResources(new ResourceDefinitionContext.Builder()
                .withKind(split[0])
                .withGroup(split[1])
                .withVersion(split[2])
                .withNamespaced(true)
                .build()).inNamespace("airflow").withName(resource.getMetadata().getLabels().get("task"));
        resourceResource.delete();
    }

    @Override
    void ErrorAction(AiOperator resource) {
        System.out.println("ErrorAction");
    }

    @Override
    void BookmarkAction(AiOperator resource) {
        System.out.println("BookmarkAction");
    }

    @Override
    public void onClose(WatcherException cause) {
        cause.printStackTrace();
    }

}
